package com.bawei.module_mine.zhibo

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_mine.R
import com.pedro.rtmp.utils.ConnectCheckerRtmp
import com.pedro.rtplibrary.rtmp.RtmpCamera1

@Route(path = "/module_mine/KaizhiboActivity")
class KaizhiboActivity : AppCompatActivity(), SurfaceHolder.Callback, ConnectCheckerRtmp {
    private lateinit var rtmpCamera1: RtmpCamera1
    private lateinit var surfaceView: SurfaceView
    private lateinit var btnStartStop: Button
    private lateinit var btnSendRedPacket: Button

    //我的个人推流地址、本机IP号、别修改
    //private val rtmpUrl = "rtmp://192.168.26.33/live/livestream"

    // 如果手机通过USB连接，使用10.0.2.2
    // 如果手机和电脑在同一WiFi，使用192.168.26.33
    private val rtmpUrl = "rtmp://192.168.26.33:8066/live/hjj123456"

    private val REQUEST_PERMISSIONS = 1234

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kaizhibo)
        surfaceView = findViewById(R.id.surfaceView)
        btnStartStop = findViewById(R.id.btnStartStop)
        btnSendRedPacket = findViewById(R.id.btn_send_red_packet)
        if (hasPermissions()) {
            initCameraPush()
        } else {
            requestPermissions()
        }
        btnStartStop.setOnClickListener {
            if (!::rtmpCamera1.isInitialized || !rtmpCamera1.isStreaming) {
                if (hasPermissions()) {
                    if (!::rtmpCamera1.isInitialized) initCameraPush()
                    startStream()
                } else {
                    requestPermissions()
                }
            } else {
                stopStream()
            }
        }
        btnSendRedPacket.setOnClickListener {
            sendRedPacket()
        }
    }

    private fun initCameraPush() {
        surfaceView.holder.addCallback(this)
        rtmpCamera1 = RtmpCamera1(surfaceView, this)
    }

    private fun hasPermissions(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.RECORD_AUDIO
                ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestPermissions() {
        ActivityCompat.requestPermissions(
            this, arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
            ), REQUEST_PERMISSIONS
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSIONS && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
            initCameraPush()
        } else {
            Toast.makeText(this, "需要摄像头和麦克风权限", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startStream() {
        if (rtmpCamera1.prepareAudio() && rtmpCamera1.prepareVideo()) {
            rtmpCamera1.startStream(rtmpUrl)
            btnStartStop.text = "停止推流"
        } else {
            Toast.makeText(this, "无法准备音视频编码器", Toast.LENGTH_SHORT).show()
        }
    }

    private fun stopStream() {
        rtmpCamera1.stopStream()
        btnStartStop.text = "开始推流"
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        // Surface 创建时可做初始化
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // Surface 改变时可做处理
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        if (rtmpCamera1.isStreaming) {
            stopStream()
        }
        rtmpCamera1.stopPreview()
    }

    // ConnectCheckerRtmp 接口实现
    override fun onConnectionSuccessRtmp() {
        Log.i("RTMP", "推流连接成功")
        runOnUiThread {
            Toast.makeText(this, "推流连接成功", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onConnectionFailedRtmp(reason: String) {
        Log.e("RTMP", "推流连接失败: $reason")
        runOnUiThread {
            Toast.makeText(this, "推流连接失败: $reason", Toast.LENGTH_SHORT).show()
            stopStream()
        }
    }

    override fun onNewBitrateRtmp(bitrate: Long) {}

    override fun onDisconnectRtmp() {
        Log.w("RTMP", "推流断开")
        runOnUiThread {
            Toast.makeText(this, "推流断开", Toast.LENGTH_SHORT).show()
            stopStream()
        }
    }

    override fun onAuthErrorRtmp() {
        Log.e("RTMP", "推流鉴权失败")
        runOnUiThread {
            Toast.makeText(this, "推流鉴权失败", Toast.LENGTH_SHORT).show()
            stopStream()
        }
    }

    override fun onAuthSuccessRtmp() {
        Log.i("RTMP", "推流鉴权成功")
        runOnUiThread {
            Toast.makeText(this, "推流鉴权成功", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onConnectionStartedRtmp(rtmpUrl: String) {
        Log.i("RTMP", "开始连接: $rtmpUrl")
        runOnUiThread {
            Toast.makeText(this, "开始连接: $rtmpUrl", Toast.LENGTH_SHORT).show()
        }
    }

    private fun sendRedPacket() {
        // TODO: 实现发红包逻辑（如通过WebSocket通知服务端）
        Toast.makeText(this, "发红包功能待实现", Toast.LENGTH_SHORT).show()
    }
}